package com.multithreading.chart1.waitAndnotify;

/**
 * @program: java-multithreading
 * @description: 旨在说明： 当前线程调用共享变量的wait方法后，只会释放当前共享变量上的锁，如果当前线程还持有其他共享变量的锁，则这些锁不会被释放。
 * @author: 陈庆彪
 * @create: 2020-06-26 19:14
 **/
public class SynchronizedTest2 {
    /**
     * @description: 创建资源
     */
    private static volatile Object resourceA= new Object();
    private static volatile Object resourceB= new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread threadA=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取resourceA共享资源的监视器锁
                    synchronized (resourceA){
                        System.out.println("ThreadA get ResourceA lock");
                        // 获取resourceB共享资源的监视器锁
                        synchronized (resourceB){
                            System.out.println("ThreadA get resourceB lock");
                            //线程A阻塞，并释放获取到的resourceA的锁
                            System.out.println("ThreadA release resourceA lock");
                            resourceA.wait();
                            //resourceB.wait();
                        }
                        resourceB.wait();
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });

        Thread threadB=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    //获取resourceA共享资源的监视器锁
                    synchronized (resourceA){
                        System.out.println("ThreadB get ResourceA lock");
                        System.out.println("ThreadB try get ResourceB lock...");
                        // 获取resourceB共享资源的监视器锁
                        synchronized (resourceB){
                            System.out.println("ThreadB get resourceB lock...");
                            //线程B阻塞，并释放获取到的resourceA的锁
                            System.out.println("ThreadB release resourceB lock");
                            resourceA.wait();
//                            resourceB.wait();
                        }
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });

        //启动线程
        threadA.start();
        threadB.start();
        //等待2个线程结束
        threadA.join();
        threadB.join();
        System.out.println("main over");
    }
}
